package com.frontop.system.modules.project.controller;

import com.github.odiszapc.nginxparser.*;
import com.google.common.base.Strings;

import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

/**
 * @author YangBoos
 * @title: Test
 * @projectName frontop-cloud
 * @description: TODO
 * @date 2021/12/22 10:40
 */
public class Test {
    public static void main(String[] args) throws IOException {
        String fileName = "F:\\workData\\nginx-1.16.1\\conf\\nginx.conf";
        try {
            NgxConfig ngxConfig = NgxConfig.read(fileName);
            NgxBlock ngxBlockHttp = ngxConfig.findBlock("http");
            List<NgxEntry> serverList = ngxBlockHttp.findAll(NgxConfig.BLOCK,"server");
            for (NgxEntry ngxEntry : serverList) {
                NgxBlock ngxBlock = (NgxBlock) ngxEntry;
                NgxParam listen = ngxBlock.findParam("listen");
                NgxParam serverName = ngxBlock.findParam("server_name");
                //找到节点
                if ("www.frontopbd.com".equals(serverName.getValue()) && "443 ssl".equals(listen.getValue())) {
                    NgxBlock ngxBlockLocation = new NgxBlock();
                    ngxBlockLocation.addValue("location");
                    ngxBlockLocation.addValue("/dasffa");
                    NgxParam ngxParam = new NgxParam();
                    ngxParam.addValue("proxy_pass http://backend_http");
                    ngxBlockLocation.addEntry(ngxParam);
                    ngxParam = new NgxParam();
                    ngxParam.addValue("proxy_set_header Host $host");
                    ngxBlockLocation.addEntry(ngxParam);
                    ngxParam = new NgxParam();
                    ngxParam.addValue("proxy_set_header X-Real-IP $remote_addr");
                    ngxBlockLocation.addEntry(ngxParam);
                    ngxParam = new NgxParam();
                    ngxParam.addValue("proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for");
                    ngxBlockLocation.addEntry(ngxParam);
                    ngxBlock.addEntry(ngxBlockLocation);
                    String content = new NgxDumper(ngxConfig).dump();
                    FileWriter fileWriter = null;
                    try {
                        fileWriter = new FileWriter(fileName);
                        fileWriter.write(content);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    } finally {
                        try {
                            fileWriter.flush();
                            fileWriter.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                        }
                    }
                    System.out.println(content);
                }
            }
        } catch (IOException e) {
        }
    }
}
